const { Result } = require("@/libs/result");
const { fileService } = require("./file.service");

class FileController {
	async upload(ctx) {
		ctx.body = await fileService.upload(ctx.req.file, ctx.state);
	}

	async deleteFile(ctx) {
		ctx.body = await fileService.deleteFile(ctx.params);
	}

	async bindBizFile(ctx) {
		ctx.body = await fileService.bindBizFile(ctx.request.body, ctx.state);
	}

	// 查询文件列表
	async queryFileByBiz(ctx) {
		ctx.body = await fileService.queryFileByBiz(ctx.params.bizId);
	}

	// 文件预览
	async previewFile(ctx) {
		const previewResult = await fileService.previewFile(ctx, ctx.params.fileName, ctx.request.query?.c || "");
		if (previewResult.error) {
            ctx.set('Content-Type', 'application/json; charset=utf-8');
			ctx.status = 404;
            ctx.body = Result.Failed(decodeURIComponent(previewResult.message));
			return;
		}
		ctx.type = previewResult.type;
		ctx.body = previewResult.body;
	}
}

module.exports = {
	fileController: new FileController()
};
